ConfirmRevRepo = new Object();

var funds = Ext.create('Ext.data.Store', {
	fields : [ 'name' ]
});

var issuers = Ext.create('Ext.data.Store', {
	fields : [ 'name' ]
});

var instruments = Ext.create('Ext.data.Store', {
	fields : [ {
		name : 'name',
		type : 'string'
	}, {
		name : 'number',
		type : 'string'
	}, {
		name : 'maturityDate',
		type : 'date',
		dateFormat : 'd/m/Y'
	} ]
});
// custom Vtype for vtype:'Rate'
Ext.apply(Ext.form.field.VTypes, {
	Rate : function(v) {
		return /^100(\.0{0,2})? *%?$|^\d{1,2}(\.\d{1,2})? *%?$/.test(v);
	},
	RateText : 'Invalid Rate',
	RateMask : /[\d\.%]/i
});

Ext.define('Collateral', {
	extend : 'Ext.data.Model',
	fields : [ {
		name : 'instrumentType',
		type : 'string'
	}, {
		name : 'instrumentNo',
		type : 'string'
	}, {
		name : 'value',
		type : 'float'
	}, {
		name : 'issuer',
		type : 'string'
	}, {
		name : 'maturityDate',
		type : 'date',
		dateFormat : 'd/m/Y'
	} ]
});

var collateralStore = new Ext.data.Store({
	model : 'Collateral',
	storeId : 'collateralStore'
});

ConfirmRevRepo.getSearchBar = function() {

	return Ext.create('Ext.form.FieldContainer', {
		items : [ {
			xtype : 'triggerfield',
			id : 'confirmRRepoTrigField',
			triggerCls : 'x-form-search-trigger',
			anchor : '28%',
			style : 'float:right;',
			emptyText : 'Search Reverse Repos',
			listeners : {
				specialkey : function(field, e) {
					if (e.getKey() == e.ENTER) {
						Ext.Msg.alert('HI', 'Press Enter');
					}
				}
			},
			onTriggerClick : function() {
				var searchResult = Ext.create('Ext.data.Store', {
					fields : [ 'id', 'dealCode', 'issuer', 'status' ]
				});
				var TrigField = Ext.ComponentQuery.query('#confirmRRepoTrigField')[0];

				Ext.Ajax.request({
					url : 'getRRepos.action',
					params : {
						queryOne : TrigField.getValue(),
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						var arrayLength = obj.deals.length;
						for (var i = 0; i < arrayLength; i++) {
							searchResult.add({
								id : obj.deals[i].id,
								dealCode : obj.deals[i].dealCode,
								issuer : obj.deals[i].issuer.code,
								name : obj.deals[i].name,
								status : obj.deals[i].status,
							});
						}
					}
				});

				var resultWindow = Ext.create('Ext.grid.Panel', {
					defaults : {
						anchor : '100%'
					},
					store : searchResult,
					columns : [ {
						text : 'Deal Code',
						dataIndex : 'dealCode',
						flex : 1
					}, {
						text : 'Issuer',
						dataIndex : 'issuer',
						flex : 1
					}, {
						text : 'Status',
						dataIndex : 'status',
						flex : 1
					} ],

					listeners : {
						itemclick : function(view, rec, item, index, eventObj) {
							var findId = rec.get('id');
							var formPanl = Ext.ComponentQuery.query('#confirmRRepoFormPanel')[0];
							formPanl.setLoading('Receiving data...', formPanl.getForm());
							var confirmFields = '';
							var rejectBtn = Ext.getCmp('confirmRRepoRejectBtn');
							var confirmBtn = Ext.getCmp('confirmRRepoConfirmBtn');

							formPanl.getForm().reset();

							Ext.Ajax.request({
								url : 'getRRepo.action',
								params : {
									id : findId,
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);

									Ext.ComponentQuery.query('#confirmRRepoDealCode')[0].setText('Deal Code :' + obj.data.dealCode);
									Ext.ComponentQuery.query('#confirmRRepoDealStatus')[0].setText('Deal Status :' + obj.data.status);

									var valDtLocal = Ext.ComponentQuery.query('#confirmRRepoValueDt')[0];
									valDtLocal.format = 'd/m/Y';
									valDtLocal.setValue(obj.data.valueDate);

									var matDtLocal = Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0];
									matDtLocal.format = 'd/m/Y';
									matDtLocal.setValue(obj.data.valueDate);

									var lblMaturityDate = Ext.ComponentQuery.query('#confirmRRepoDuration')[0];
									var durationDays = (matDtLocal.getValue() - valDtLocal.getValue()) / 86400000;
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));

									formPanl.getForm().load({
										url : 'getRRepo.action',
										params : {
											id : findId,
										},
										success : function(response) {
											formPanl.setLoading(false);
											ConfirmRevRepo.setMatVal();
											if (rec.get('status') === 'Initial') {
												Ext.Ajax.request({
													url : 'confFields.action',
													params : {
														screen : 'RecordRevRepo',
													},
													success : function(response) {
														var objFive = Ext.decode(response.responseText);
														confirmFields = objFive.values;
														formPanl.getForm().getFields().each(function(field) {
															field.setDisabled(true);
														});
														var confFieldsArrray = confirmFields.split(";");
														var i;
														var confFieldLocal;
														var confFieldQuery;
														for (i = 0; i < confFieldsArrray.length - 1; i++) {
															confFieldQuery = '#' + confFieldsArrray[i];
															confFieldLocal = Ext.ComponentQuery.query(confFieldQuery)[0];
															confFieldLocal.enable();
															confFieldLocal.reset();
														}
														Ext.ComponentQuery.query('#confirmRRepoResWindow')[0].close();
														Ext.ComponentQuery.query('#confirmRRepoTrigField')[0].enable();
														formPanl.setLoading(false);
													},
													failure : function(form, action) {
														formPanl.setLoading(false);
														Ext.Msg.alert('Error!', 'Failed to load Confirmation Fields!');
													}
												});

											} else {
												Ext.ComponentQuery.query('#confirmRRepoFundCmb')[0].disable();
												Ext.ComponentQuery.query('#confirmRRepoResWindow')[0].close();
												Ext.ComponentQuery.query('#confirmRRepoTrigField')[0].enable();
												formPanl.setLoading(false);
											}
											// ConfirmRevRepo.setMatVal();

										},
										failure : function(form, action) {
											formPanl.setLoading(false);
											Ext.Msg.alert("An Error occured. Load failed");
										}
									});

								},
								failure : function(form, action) {
									formPanl.setLoading(false);
								}
							});

							if (rec.get('status') === 'Confirmed') {
								formPanl.getForm().getFields().each(function(field) {
									field.setDisabled(true);
								});
								rejectBtn.disable();
								confirmBtn.disable();
							} else {
								if (rec.get('status') === 'Initial') {
									confirmBtn.enable();
									rejectBtn.enable();
								} else {
									rejectBtn.disable();
									confirmBtn.disable();
								}
							}
							// this.up('.window').close();
							Ext.ComponentQuery.query('#confirmRRepoTrigField')[0].enable();
							// formPanl.setLoading(false);

						}

					}
				});

				Ext.create('Ext.window.Window', {
					title : 'Sales',
					id : 'confirmRRepoResWindow',
					height : 330,
					frame : true,
					width : 500,
					constrain : true,
					resizable : false,
					layout : {
						type : 'fit'
					},
					items : [ resultWindow ]
				}).show();

			}
		} ]
	});
};

ConfirmRevRepo.getFieldSet1 = function() {

	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'fundName',
			type : 'string',
		}, {
			name : 'fundCode',
			type : 'string',
		} ],
		storeId : 'confirmRRepoFundStore',
	});

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'RREPO',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('confirmRRepoFundStore').loadRawData(obj.fundList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'name',
			type : 'string',
		}, {
			name : 'code',
			type : 'string',
		} ],
		storeId : 'confirmRRepoIssuerStore',
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('confirmRRepoIssuerStore').loadRawData(obj.issuerList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
		}

	});

	var selectFundComboBox = Ext.create('Ext.form.ComboBox', {
		id : 'confirmRRepoFundCmb',
		name : 'fund',
		fieldLabel : 'Fund',
		store : Ext.data.StoreManager.lookup('confirmRRepoFundStore'),
		valueField : 'id',
		queryMode : 'local',
		autoScroll : true,
		allowBlank : false,
		msgTarget : 'under',
		flex : 1,
		labelWidth : 120,
		padding : '0 5 0 0',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{fundName} - <b>{fundCode}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{fundName}', '</tpl>'),
	});

	var selectIssuerComboBox = Ext.create('Ext.form.ComboBox', {
		id : 'confirmRRepoIssuer',
		name : 'issuer',
		fieldLabel : 'Issuer',
		store : Ext.data.StoreManager.lookup('confirmRRepoIssuerStore'),
		valueField : 'id',
		queryMode : 'local',
		autoScroll : true,
		allowBlank : false,
		flex : 1,
		padding : '0 5 0 0',
		msgTarget : 'under',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name} - <b>{code}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'confirmRRepoDealCode',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectFundComboBox, selectIssuerComboBox ]
		}, {
			xtype : 'label',
			id : 'confirmRRepoDealStatus',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Value Date',
				name : 'valueDate',
				id : 'confirmRRepoValueDt',
				flex : 1,
				padding : '0 5 0 0',
				labelWidth : 120,
				allowBlank : false,
				blankText : 'Please enter a Start Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							var dfMaturityDate = Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0];
							if (dfMaturityDate.getValue() != null) {
								var lblMaturityDate = Ext.ComponentQuery.query('#confirmRRepoDuration')[0];
								if (this.getValue() > dfMaturityDate.getValue()) {
									Ext.MessageBox.alert('Error', 'Value Date cannot be greater than Maturity Date.');
									this.setValue(null);
									lblMaturityDate.setText('');
								} else {
									var durationDays = (dfMaturityDate.getValue() - this.getValue()) / 86400000;
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									ConfirmRevRepo.setMatVal();
								}

							}

						}
					}
				}
			}, {
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				id : 'confirmRRepoMaturityDt',
				name : 'maturityDate',
				flex : 1,
				padding : '0 5 0 0',
				// style:'margin-left:5px;',
				allowBlank : false,
				blankText : 'Please enter a Maturity Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							// var btnColAdd =
							// Ext.ComponentQuery.query('#recRevRepoAddColBtn')[0];
							var dfValueDate = Ext.ComponentQuery.query('#confirmRRepoValueDt')[0];
							if (dfValueDate.getValue() != null) {
								var lblValueDate = Ext.ComponentQuery.query('#confirmRRepoDuration')[0];
								if (dfValueDate.getValue() > this.getValue()) {
									Ext.MessageBox.alert('Error', 'Maturity Date cannot be smaller than Value Date.');
									this.setValue(null);
									lblValueDate.setText('');
								} else {
									// btnColAdd.enable();
									var durationDays = (this.getValue() - dfValueDate.getValue()) / 86400000;
									lblValueDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									ConfirmRevRepo.setMatVal();
								}

							}
						}
					}
				}
			} ]
		}, {
			xtype : 'label',
			id : 'confirmRRepoDuration'
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Delevary Method',
				store : CommenStore.delevaryMethodStore,
				valueField : 'id',
				flex : 1,
				labelWidth : 120,
				name : 'delevarymethode',
				id : 'confirmRRepoDelevaryMethod',
				padding : '0 5 0 0',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Dealer',
				store : CommenStore.dealersStore,
				valueField : 'id',
				flex : 1,
				padding : '0 5 0 0',
				name : 'dealerCode',
				id : 'confirmRRepoDealer',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{name}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			} ]
		}, {
			xtype : 'combo',
			labelWidth : 120,
			fieldLabel : 'Settlement Method',
			store : CommenStore.settlmentStore,
			valueField : 'id',
			anchor : '50%',
			name : 'settlementCode',
			id : 'confirmRRepoSettlementMethod',
			padding : '0 10 0 0',
			displayField : 'code',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
			listeners : {
				change : function(combo, record, index) {
					if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
						combo.setValue(null);
					}
				}
			}
		} ]
	});
	return finalFieldSet;
};

ConfirmRevRepo.getFieldSet2 = function() {

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Parameters',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			defaultType : 'numberfield',
			items : [ {
				xtype : 'textfield',
				minValue : 0,
				name : 'principleValue',
				padding : '0 5 0 0',
				allowBlank : false,
				id : 'confirmRRepoPrincipleVal',
				fieldLabel : 'Principle Value',
				flex : 1,
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.00'));
						ConfirmRevRepo.setMatVal();
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.00'));
					}
				}
			}, {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				name : 'actualRate',
				id : 'confirmRRepoActualRate',
				fieldLabel : 'Actual Rate',
				flex : 1,
				padding : '0 5 0 0',
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						ConfirmRevRepo.setMatVal();
					},
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			defaultType : 'numberfield',
			items : [ new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'dayBasis' ],
					data : [ {
						"dayBasis" : "Act / Act"
					}, {
						"dayBasis" : "Act / 360"
					}, {
						"dayBasis" : "Act / 364"
					}, {
						"dayBasis" : "Act / 365"
					}, {
						"dayBasis" : "30 / 360"
					}, {
						"dayBasis" : "30 / 365"
					} ]
				}),
				displayField : 'dayBasis',
				valueField : 'dayBasis',
				mode : 'local',
				value : 'Act / 365',
				fieldLabel : 'Day Basis',
				forceSelection : true,
				flex : 4,
				padding : '0 5 0 0',
				name : 'dayBasis',
				id : 'confirmRRepoDayBasis',
				listeners : {
					select : {
						fn : function(combo, value) {
							ConfirmRevRepo.setMatVal();
						}
					}
				},
			}), {
				xtype : 'label',
				flex : 2,
				style : 'margin-top:3px;',
				text : 'Maturity Value:',
			}, {
				xtype : 'label',
				flex : 2,
				id : 'confirmRRepoDealMatValLbl',
				style : 'font-weight:600;margin-top:3px;',
			} ]
		} ]
	});
	return finalFieldSet;
};

ConfirmRevRepo.getFieldSet3 = function() {
	var selectInsTypeComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'instrumentType',
		id : 'recRevRepoInstrumentType',
		fieldLabel : 'Instrument Type',
		store : instrumentTypes,
		valueField : 'type',
		autoScroll : true,
		allowBlank : false,
		flex : 1,
		padding : '0 5 0 0',
		// style:'margin-left:5px;',
		blankText : 'Please select an Instrument Type to proceed',
		msgTarget : 'under',
		editable : false,
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{type}</div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{type}', '</tpl>'),
		listeners : {
			select : {
				fn : function(combo, value) {
					var comboInsCode = Ext.ComponentQuery.query('#recRevRepoInsNo')[0];
					var prDealer = Ext.ComponentQuery.query('#recRevRepoPrimDealer')[0];
					var issuer = Ext.ComponentQuery.query('#recRevRepoIssuer')[0];
					var dfColMaturityDate = Ext.ComponentQuery.query('#recRevRepoColMatDt')[0];
					var cbInsNo = Ext.ComponentQuery.query('#recRevRepoInsNo')[0];
					prDealer.clearValue();
					issuer.clearValue();
					instrumentStore.clearFilter(true);
					if (instrumentTypes.getAt(instrumentTypes.find('type', combo.getValue())).get('listed') === '1') {
						instrumentStore.filter('type', instrumentTypes.getAt(instrumentTypes.find('type', combo.getValue())).get('type'));
						issuer.disable();
						prDealer.disable();
						dfColMaturityDate.disable();
						cbInsNo.setEditable(false);
					} else {
						cbInsNo.setEditable(true);
						instrumentStore.filter('type', 'unlisted');
						dfColMaturityDate.enable();
						if (instrumentTypes.getAt(instrumentTypes.find('type', combo.getValue())).get('issuer') === 'government') {
							issuer.disable();
							prDealer.enable();
						} else {
							prDealer.disable();
							issuer.enable();
						}
					}
					comboInsCode.clearValue();
					comboInsCode.bindStore(instrumentStore);
					comboInsCode.show();
				}
			}
		}

	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Collateral Information',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectInsTypeComboBox, Ext.create('Ext.form.ComboBox', {
				fieldLabel : 'Instrument No',
				store : instrumentStore,
				valueField : 'code',
				displayField : 'name',
				id : 'recRevRepoInsNo',
				autoScroll : true,
				queryMode : 'local',
				allowBlank : false,
				blankText : 'Please select an Instrument to proceed',
				msgTarget : 'under',
				editable : true,
				flex : 1,
				padding : '0 5px 0 0',
				// style:'margin-left:5px;',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {
							var repInsCmb = Ext.ComponentQuery.query('#recRevRepoInstrumentType')[0];
							var repPrimaryDealer = Ext.ComponentQuery.query('#recRevRepoPrimDealer')[0];
							var repIssuerCB = Ext.ComponentQuery.query('#recRevRepoIssuer')[0];
							if (instrumentTypes.getAt(instrumentTypes.find('type', repInsCmb.getValue())).get('issuer') === 'government') {
								repPrimaryDealer.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('issuer'));
								repIssuerCB.clearValue();
							} else {
								repIssuerCB.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('issuer'));
								repPrimaryDealer.clearValue();
							}

							var dfColMaturityDate = Ext.ComponentQuery.query('#recRevRepoColMatDt')[0];
							dfColMaturityDate.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('maturityDate'));
							dfColMaturityDate.disable();
						}
					}
				}
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ Ext.create('Ext.form.ComboBox', {
				name : 'issuer',
				fieldLabel : 'Issuer',
				store : issuers,
				valueField : 'name',
				autoScroll : true,
				flex : 1,
				padding : '0 5px 0 0',
				// style:'margin-top:5px;margin-left:5px;',
				id : 'recRevRepoIssuer',
				allowBlank : false,
				blankText : 'Please select an Issuer to proceed',
				msgTarget : 'under',
				editable : true,
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
			}), Ext.create('Ext.form.ComboBox', {
				fieldLabel : 'Primary Dealer',
				store : primaryDealerStore,
				valueField : 'name',
				id : 'recRevRepoPrimDealer',
				autoScroll : true,
				queryMode : 'local',
				editable : false,
				flex : 1,
				padding : '0 5px 0 0',
				// style:'margin-top:5px;',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				id : 'recRevRepoColMatDt',
				allowBlank : false,
				flex : 1,
				padding : '0 5px 0 0',
				style : 'margin-bottom:10px;',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
			}, {
				xtype : 'numberfield',
				minValue : 0,
				name : 'insValue',
				id : 'recRevRepoInsValue',
				fieldLabel : 'Face Value',
				flex : 1,
				allowBlank : false,
				padding : '0 5px 0 0',
				style : 'margin-bottom:10px;',
				blankText : 'Please enter the Value',
				msgTarget : 'under'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'fit',
			style : 'margin-left:5px;margin-top:10px;',
			items : [ Ext.create('Ext.grid.Panel', {
				id : 'recRevRepoCollateralPanel',
				store : Ext.data.StoreManager.lookup('collateralStore'),
				columns : [ {
					text : 'Instrument Type',
					dataIndex : 'instrumentType',
					flex : 1
				}, {
					text : 'Instrument No',
					dataIndex : 'instrumentNo',
					flex : 1
				}, {
					text : 'Issuer/PrDealer',
					dataIndex : 'issuer',
					flex : 1
				}, {
					xtype : 'datecolumn',
					format : 'd-m-Y',
					text : 'Maturity',
					dataIndex : 'maturityDate',
					flex : 1
				}, {
					text : 'Value',
					dataIndex : 'value',
					flex : 1
				} ],
				height : 250,
				width : 450,
				dockedItems : [ {
					xtype : 'pagingtoolbar',
					id : 'recRevRepoColGridToolBar',
					store : Ext.data.StoreManager.lookup('collateralStore'),
					dock : 'bottom',
					displayInfo : true
				} ],
				tbar : [ '->', {
					text : 'Add',
					id : 'recRevRepoAddColBtn',
					disabled : true,
					handler : function() {
						var revRepMatDate = Ext.ComponentQuery.query('#recRevRepoMaturityDate')[0];
						var revRepColMatDate = Ext.ComponentQuery.query('#recRevRepoColMatDt')[0];
						var cbInsType = Ext.ComponentQuery.query('#recRevRepoInstrumentType')[0];
						var tfInsNo = Ext.ComponentQuery.query('#recRevRepoInsNo')[0];
						var tfInsVal = Ext.ComponentQuery.query('#recRevRepoInsValue')[0];
						var cbPrimaryDealer = Ext.ComponentQuery.query('#recRevRepoPrimDealer')[0];
						var tfIssuer = Ext.ComponentQuery.query('#recRevRepoIssuer')[0];
						if (cbInsType.getValue() === null) {
							Ext.MessageBox.alert('Error', 'Please select an Instrument type.');
						} else if (tfInsNo.getValue() === '' || tfInsNo.getValue() === null) {
							Ext.MessageBox.alert('Error', 'Please enter the Instrument Number.');
						} else if (tfInsVal.getValue() === 0 || tfInsVal.getValue() === null) {
							Ext.MessageBox.alert('Error', 'Please check the Instrument Value.');
						} else if (cbPrimaryDealer.getValue() === null && (tfIssuer.getValue() === null || tfIssuer.getValue() === '')) {
							Ext.MessageBox.alert('Error', 'Issuer/Primary Dealer is requered.');
						} else {
							if (revRepColMatDate.getValue() < revRepMatDate.getValue()) {
								Ext.Msg.confirm('Confirm Box', 'Collateral Matures too early! Do you wish to continue?', function(buttonText) {
									if (buttonText == "yes") {
										var recordIndex = collateralStore.findBy(function(record, id) {
											if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
												return true;
											}
											return false;
										});
										if (recordIndex != -1) {
											Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
										} else {
											var userco = Ext.ModelManager.create({
												instrumentType : cbInsType.getValue(),
												instrumentNo : tfInsNo.getValue(),
												value : tfInsVal.getValue(),
												issuer : (cbPrimaryDealer.getValue() === null) ? tfIssuer.getValue() : cbPrimaryDealer.getValue(),
												maturityDate : revRepColMatDate.getValue()
											}, 'Collateral');
											collateralStore.add(userco);
											var pagingToolbar = Ext.ComponentQuery.query('#recRevRepoColGridToolBar')[0];
											collateralStore.totalCount = collateralStore.count();
											pagingToolbar.onLoad();
										}
									}
								});
							} else {
								var recordIndex = collateralStore.findBy(function(record, id) {
									if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
										return true;
									}
									return false;
								});
								if (recordIndex != -1) {
									Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
								} else {
									var userco = Ext.ModelManager.create({
										instrumentType : cbInsType.getValue(),
										instrumentNo : tfInsNo.getValue(),
										value : tfInsVal.getValue(),
										issuer : (cbPrimaryDealer.getValue() === null) ? tfIssuer.getValue() : cbPrimaryDealer.getValue(),
										maturityDate : revRepColMatDate.getValue()
									}, 'Collateral');
									collateralStore.add(userco);
									var pagingToolbar = Ext.ComponentQuery.query('#recRevRepoColGridToolBar')[0];
									collateralStore.totalCount = collateralStore.count();
									pagingToolbar.onLoad();
								}
							}
						}
					}
				}, {
					text : 'Remove',
					handler : function() {

						var collateralsStore = Ext.data.StoreManager.lookup('collateralStore');
						var pCpnDtStorePanel = Ext.ComponentQuery.query('#recRevRepoCollateralPanel')[0];

						var sm = pCpnDtStorePanel.getSelectionModel();
						var sel = sm.getSelection();
						pCpnDtStorePanel.store.remove(sel[0]);

						var pagingToolbar = Ext.ComponentQuery.query('#recRevRepoColGridToolBar')[0];
						collateralsStore.totalCount = collateralsStore.count();
						pagingToolbar.onLoad();
					}
				} ]

			}) ]
		} ]
	});
	return finalFieldSet;
};

ConfirmRevRepo.getCenterPanel = function() {
	var searchBar = ConfirmRevRepo.getSearchBar();
	var filedset1 = ConfirmRevRepo.getFieldSet1();
	var filedset2 = ConfirmRevRepo.getFieldSet2();
	// var filedset3 = ConfirmRevRepo.getFieldSet3();

	CommenStore.settlmentStore.load();
	CommenStore.dealersStore.load();
	CommenStore.delevaryMethodStore.load();

	var formPanel = Ext.create('Ext.form.FormPanel', {
		id : 'confirmRRepoFormPanel',
		bodyPadding : '20',
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 175,
			anchor : '72%',
		},
		fieldDefaults : {
			labelAlign : 'left',
			labelWidth : 150,
		},
		title : 'Record Reverse REPO',
		items : [ searchBar, filedset1, filedset2, /* filedset3 */],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				App.Core.setScreen(ConfirmRevRepo.getCenterPanel());
			}
		}, {
			text : 'Reject',
			id : 'confirmRRepoRejectBtn',
			itemId : 'rejectButton',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'rejectRRepo.action';
				formPanel.setLoading('Rejecting...');
				formPanel.getForm().getFields().each(function(field) {
					field.setDisabled(true);
				});
				var dealCode = Ext.ComponentQuery.query('#confirmRRepoDealCode')[0].text.substr(11);
				form.submit({
					params : {
						'user' : 'createdUser',
						'dealCode' : dealCode,
					},
					success : function(form, action) {
						form.reset();
						Ext.Msg.alert('Success', dealCode + ' : Repo Rejected.');
						Ext.ComponentQuery.query('#confirmRRepoDuration')[0].setText('');
						Ext.ComponentQuery.query('#confirmRRepoDealCode')[0].setText('');
						Ext.ComponentQuery.query('#confirmRRepoDealStatus')[0].setText('');
						Ext.ComponentQuery.query('#confirmRRepoDealMatValLbl')[0].setText('');
						Ext.getCmp('confirmRRepoRejectBtn').disable();
						Ext.getCmp('confirmRRepoConfirmBtn').disable();
						formPanel.setLoading(false);
					},
					failure : function(form, action) {
						Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
						formPanel.setLoading(false);
					}
				});
			}
		}, {

			text : 'Confirm',
			id : 'confirmRRepoConfirmBtn',
			itemId : 'confirmButton',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'confRRepo.action';

				Ext.ComponentQuery.query('#confirmRRepoFundCmb')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoIssuer')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoValueDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoPrincipleVal')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoActualRate')[0].enable();
				Ext.ComponentQuery.query('#confirmRRepoDayBasis')[0].enable();

				if (form.isValid()) {
					formPanel.setLoading('Confirming...');

					var valueDtField = Ext.ComponentQuery.query('#confirmRRepoValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0];
					var dealCode = Ext.ComponentQuery.query('#confirmRRepoDealCode')[0].text.substr(11);

					form.submit({
						params : {
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'user' : 'confirmedUser',
							'dealCode' : dealCode,
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', 'Reverse REPO Confirmed.<br> Deal Code <b>' + action.result.dealCode + '</b>');
							formPanel.setLoading(false);
							Ext.ComponentQuery.query('#confirmRRepoDuration')[0].setText('');
							Ext.ComponentQuery.query('#confirmRRepoDealCode')[0].setText('');
							Ext.ComponentQuery.query('#confirmRRepoDealStatus')[0].setText('');
							Ext.ComponentQuery.query('#confirmRRepoDealMatValLbl')[0].setText('');
							Ext.getCmp('confirmRRepoRejectBtn').disable();
							Ext.getCmp('confirmRRepoConfirmBtn').disable();
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert("ERROR!", "Form Incomplete. Please check!");
				}
			}
		} ]
	});
	return formPanel;
};

ConfirmRevRepo.setMatVal = function() {
	var valueDt = Ext.ComponentQuery.query('#confirmRRepoValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	var principleValue = Ext.ComponentQuery.query('#confirmRRepoPrincipleVal')[0].getValue();
	if (principleValue == '' || principleValue == null)
		return;

	var dayBasis = Ext.ComponentQuery.query('#confirmRRepoDayBasis')[0].getValue();
	if (dayBasis == null)
		return;

	var actualRate = Ext.ComponentQuery.query('#confirmRRepoActualRate')[0].getValue();
	if (actualRate == null)
		return;

	Ext.Ajax.request({
		url : 'evalRevRepo.action',
		params : {
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'principleValue' : principleValue,
			'actualRate' : actualRate,
			'dayBasis' : dayBasis,
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#confirmRRepoDealMatValLbl')[0].setText(obj.maturityValue);
		},
		failure : function(response) {
			Ext.ComponentQuery.query('#recFdFaceValue')[0].setValue('Error :' + obj.status);
		},
	});
};

ConfirmRevRepo.setMatValPrev = function() {
	var valueDt = Ext.ComponentQuery.query('#confirmRRepoValueDt')[0].getValue();
	if (valueDt == null)
		return;
	var maturityDt = Ext.ComponentQuery.query('#confirmRRepoMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;
	var prValStr = Ext.ComponentQuery.query('#confirmRRepoPrincipleVal')[0].getValue();
	if (prValStr == null || prValStr === '')
		return;
	var ActRate = Ext.ComponentQuery.query('#confirmRRepoActualRate')[0].getValue();
	if (ActRate == null)
		return;
	var dayBasis = Ext.ComponentQuery.query('#confirmRRepoDayBasis')[0].getValue();
	if (dayBasis == null)
		return;

	var dur = (maturityDt - valueDt) / 86400000;
	var prVal = parseFloat(prValStr.replace(/\,/g, ''));
	var res = ((prVal * ActRate * dur) / (100 * 365)).toFixed(4);
	Ext.ComponentQuery.query('#confirmRRepoDealMatValLbl')[0].setText(res);
	return (res);
};

ConfirmRevRepo.getRollOverDeal = function(fund, issuer, valueDate, principaleValue) {
	var panel = ConfirmRevRepo.getCenterPanel();
	var tmpfundStore = Ext.data.StoreManager.lookup('confirmRRepoFundStore');
	var tmpissuersStore = Ext.data.StoreManager.lookup('confirmRRepoIssuerStore');
	tmpfundStore.removeAll();
	tmpissuersStore.removeAll();

	var tmpIssuerCmb = Ext.getCmp('confirmRRepoIssuer');
	var fundCmb = Ext.getCmp('confirmRRepoFundCmb');
	var tmpValDt = Ext.getCmp('confirmRRepoValueDt');
	var tmpDealValue = Ext.getCmp('confirmRRepoPrincipleVal');

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'RREPO',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tmpfundStore.loadRawData(obj.fundList);
			fundCmb.setValue(tmpfundStore.getAt(tmpfundStore.find('fundCode', fund)).get('id'));
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tmpissuersStore.loadRawData(obj.issuerList);
			tmpIssuerCmb.setValue(tmpissuersStore.getAt(tmpissuersStore.find('code', issuer)).get('id'));
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
		}

	});

	// Ext.getCmp('recRepoIssuer').setValue(issuer);
	tmpValDt.setValue(valueDate);
	tmpDealValue.setValue(principaleValue);
	return panel;
};
